package xyz.xiaoshengfu.xrpc.provider;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import xyz.xiaoshengfu.xrpc.common.JsonUtils;
import xyz.xiaoshengfu.xrpc.config.ProviderServiceInfor;
import xyz.xiaoshengfu.xrpc.config.ServiceBean;
import xyz.xiaoshengfu.xrpc.data.XRpcResources;

/**
 * <p>Title: XRpcProviderRegisterClient</p>
 * <p>Description:xRPC服务提供者注册客户端 </p>
 * @author xiaoshengfu(2439323118@qq.com)
 * @date 2020年3月24日
 */
public class XRpcProviderRegisterClient {

	private List<ProviderServiceInfor> providerServiceInforList;

	public XRpcProviderRegisterClient() {
		super();
		providerServiceInforList = new ArrayList<ProviderServiceInfor>(
				XRpcResources.xRpcConfig.getServiceBeanList().size());
		for (ServiceBean serviceBean : XRpcResources.xRpcConfig.getServiceBeanList()) {
			providerServiceInforList.add(new ProviderServiceInfor(ProviderServiceInfor.OK,
					XRpcResources.xRpcConfig.getApplicationConfig().getHostAddress(),
					XRpcResources.xRpcConfig.getProtocolConfig().getPort(),
					XRpcResources.xRpcConfig.getApplicationConfig().getName(), serviceBean));
		}
	}

	public void providerScheduledRegister() {
		providerFirstRegister();
		Executors.newScheduledThreadPool(1).scheduleWithFixedDelay(() -> {
			providerRegister();
		}, 0L, 120L, TimeUnit.SECONDS);
	}

	private void providerRegister() {
		for (int i = 0; i < providerServiceInforList.size(); i++) {
			XRpcResources.getJedisClientPool()
					.setex("xRpcProvider_" + XRpcResources.getLocalApplicationName() + ":"
							+ providerServiceInforList.get(i).getServiceBean().getServiceInterface(), 180,
							JsonUtils.objectToJson(providerServiceInforList.get(i)));
		}
	}

	private void providerFirstRegister() {
		for (int i = 0; i < providerServiceInforList.size(); i++) {
			XRpcResources.getJedisClientPool().publisher(
					providerServiceInforList.get(i).getServiceBean().getServiceInterface(),
					JsonUtils.objectToJson(providerServiceInforList.get(i)));
		}
	}

}
